package com.example.chat_websocket.config;

import javax.websocket.Session;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 此类为线程池
 */
public class SessionPool {

    // String为用户标识，可以理解为username
    // Session为会话连接，由系统自动创建
    // ConcurrentHashMap集合为线程安全，并且高性能
    public static Map<String, Session> sessions = new ConcurrentHashMap<>();

    public static void close(String sessionId)throws IOException{
        javax.websocket.Session session = sessions.get(sessionId);
        if (session != null){
            sessions.get(sessionId).close();
        }
    }

    // 遍历所有用户，并把message发送给所有用户
    public static void sendMessage(String message, String myUsername){
        for (String sessionId : SessionPool.sessions.keySet()){
            String myUsername_CH = null; // 解决中文乱码
            try {
                myUsername_CH = URLDecoder.decode(myUsername, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            SessionPool.sessions.get(sessionId).getAsyncRemote().sendText(myUsername_CH+":"+message);
        }
    }

    // 给指定用户发送
    public static void setSessions(Map<String,Object> params, Session my_session){
        String toUsername = params.get("toUsername").toString();
        String msg = params.get("msg").toString();
        String fromUsername = params.get("fromUsername").toString();
        String fromUsername_CH = null; // 解决中文乱码
        try {
            fromUsername_CH = URLDecoder.decode(fromUsername, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        msg = "来自" + fromUsername_CH + "的消息: " + msg;
        Session session = sessions.get(toUsername);
        if (session != null){
            session.getAsyncRemote().sendText(msg);

            my_session.getAsyncRemote().sendText(msg);
        }
    }
}
